package core.util.logging;

import core.util.date.DateUtil;
import core.util.logging.constants.Location;
import core.util.logging.screen.ScreenCapture;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class SimpleLogger {
    private static SimpleLogger logger;

    private static boolean screenCapFlag = false;

    public static void setScreenCap( boolean screenCap ) {
        screenCapFlag = screenCap;
    }

    /*
     * time, object being acted upon, window panel, action, screenshot file name
     */
    private static final String LOG_FORMATTER = "%s\t%s\t%s\t%s\t%s";

    private BufferedWriter out = null;

    private SimpleLogger() throws IOException {
        // append instead of overwrite
        out = new BufferedWriter( new FileWriter( "log.dat", true ) );
    }

    public void log( String object, Location location, String action ) {
        String now = DateUtil.now();
        String time = Long.toString( System.currentTimeMillis() );
        // take a screenshot of current state
        if( screenCapFlag ) {
            ScreenCapture.takeScreenShot( time );
        }
        String line = String.format( LOG_FORMATTER, now, object, location,
                action, ScreenCapture.getFileDirectory() + File.separator
                        + time + ".png" );
        try {
            out.write( line );
            out.newLine();
            out.flush();
            System.out.println( line );
        } catch( IOException e ) {
            e.printStackTrace();
        }
    }

    public void log( Location location, String action ) {
        log( "<none selected>", location, action );
    }

    public static SimpleLogger getLogger() {
        if( logger == null ) {
            try {
                logger = new SimpleLogger();
            } catch( IOException e ) {
                e.printStackTrace();
            }
        }
        return logger;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if( out != null ) {
            out.close();
        }
    }

}
